package cn.aaa.service.impl;

import cn.aaa.constants.CacheConstants;
import cn.aaa.mapper.DriverSettingMapper;
import cn.aaa.pojo.bo.DriverGeoBo;
import cn.aaa.pojo.domain.DriverSetting;
import cn.aaa.pojo.domain.RedisDriverSetting;
import cn.aaa.service.IDriverWorkService;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class DriverWorkServiceImpl implements IDriverWorkService {
    @Autowired
    private DriverSettingMapper driverSettingMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public void onLine() {
        long id = StpUtil.getLoginIdAsLong();//司机id
        //查询司机的配置
        DriverSetting driverSetting = driverSettingMapper.selectById(id);
        //创建司机配置
        RedisDriverSetting redisDriverSetting = new RedisDriverSetting();
        //复制司机配置
        BeanUtils.copyProperties(driverSetting,redisDriverSetting);
        String key = String.format(CacheConstants.KEY_DRIVER_ONLINE, id);
        //设置过期时间5h
        redisTemplate.opsForValue().set(key,redisDriverSetting,5, TimeUnit.HOURS);
    }
//    司机下线
    @Override
    public void offLine(Long id) {
        redisTemplate.delete(String.format(CacheConstants.KEY_DRIVER_ONLINE, id));
        redisTemplate.opsForGeo().remove(CacheConstants.GEO , StpUtil.getLoginIdAsLong());
    }

    @Override
    public void geo(DriverGeoBo driverGeoBo) {
        Point point = new Point(driverGeoBo.getLongitude(), driverGeoBo.getLatitude());
        Long add = redisTemplate.opsForGeo().add(CacheConstants.GEO, point, StpUtil.getLoginIdAsLong());
        if(add == 1){
            //重置过期时间
            String key = String.format(CacheConstants.KEY_DRIVER_ONLINE, StpUtil.getLoginIdAsLong());
            redisTemplate.expire(key,5,TimeUnit.HOURS);
        }
    }
}
